//
//  NSMutableURLRequest+convenience.m
//  KFD
//
//  Created by JIRENTIANXIANG on 6/5/15.
//  Copyright (c) 2015 KFD. All rights reserved.
//

#import "NSMutableURLRequest+convenience.h"
#import "NSURL+convenience.h"
#import "KFDEncryptor.h"

//#define KFD_DEBUG

@implementation NSMutableURLRequest (convenience)

+(NSMutableURLRequest*)requestWithMethod:(NSString *)method url:(NSURL *)url
{
    NSMutableURLRequest* request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:8];
    request.HTTPMethod=method;
    return request;
}

+(NSDictionary*)fullParametersWithParameters:(NSDictionary*)parameters
{
    long time=(long)[NSDate date].timeIntervalSince1970;
    NSString* timeStr=[NSString stringWithFormat:@"%ld",time];
    NSMutableDictionary* fullParams=@{@"os":@"ios",@"version":@"1.0.7",@"time":timeStr}.mutableCopy;
    NSArray* keys=parameters.allKeys;
    for (NSString* key in keys) {
        fullParams[key] = parameters[key];
    }
    return fullParams;
}

+(NSMutableURLRequest*)getRequestWithURL:(NSString *)baseURL parameters:(NSDictionary *)parameters
{
    NSURL* url=[NSURL urlWithBaseURL:baseURL parameters:[NSMutableURLRequest fullParametersWithParameters:parameters]];
    return [NSMutableURLRequest requestWithMethod:@"GET" url:url];
}

+(NSMutableURLRequest*)getRequestWithURL:(NSString *)baseURL parameters:(NSDictionary *)parameters signature:(NSString *)signature
{
    NSURL* url=[NSURL urlWithBaseURL:baseURL parameters:[NSMutableURLRequest fullParametersWithParameters:parameters] signature:signature];
    return [NSMutableURLRequest requestWithMethod:@"GET" url:url];
}

+(NSMutableURLRequest*)postRequestWithURL:(NSString *)url bodyParameters:(NSDictionary *)parameters
{
    NSMutableURLRequest* request=[NSMutableURLRequest requestWithMethod:@"POST" url:[NSURL URLWithString:url]];
    NSDictionary* fullParams=[NSMutableURLRequest fullParametersWithParameters:parameters];
    NSString* body=[KFDEncryptor autoSignedParameterListForParameters:fullParams];
    request.HTTPBody=[body dataUsingEncoding:NSUTF8StringEncoding];
    return request;
}

+(NSMutableURLRequest*)postRequestWithURL:(NSString *)baseURL urlParameters:(NSDictionary *)parameters
{
    NSURL* url=[NSURL urlWithBaseURL:baseURL parameters:[NSMutableURLRequest fullParametersWithParameters:parameters]];
    return [NSMutableURLRequest requestWithMethod:@"POST" url:url];
    
}

+(NSMutableURLRequest*)postRequestWithURL:(NSString *)url bodyParameters:(NSDictionary *)parameters signature:(NSString *)signature
{
    NSMutableURLRequest* request=[NSMutableURLRequest requestWithMethod:@"POST" url:[NSURL URLWithString:url]];
    NSDictionary* fullParams=[NSMutableURLRequest fullParametersWithParameters:parameters];
    NSString* body=[KFDEncryptor signedParameterListForParameters:fullParams withSignature:signature];
    request.HTTPBody=[body dataUsingEncoding:NSUTF8StringEncoding];
    return request;
}

@end
